import { stringify } from 'querystring';
import { history } from 'umi';
import { fakeAccountLogin,threeAccountLogin,codeAccountLogin } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { notification } from 'antd'
const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      const { type } = payload
      const response = type == 'account' ? yield call(fakeAccountLogin, payload)
      : yield call(threeAccountLogin,payload)
      if(response.token){
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        }); // Login successfully
        history.replace('/');

      }
    },
    *codeLogin({ payload }, { call, put }) {
      const response =  yield call(threeAccountLogin,payload)
      if(response.status == '400'){
        history.replace('/user/login');
      }
      if(response.token){
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        }); // Login successfully
        history.replace('/');

      }
    },

    logout() {
      const { redirect } = getPageQuery(); // Note: There may be security issues, please note
      // 清除缓存
      localStorage.clear();
      if (window.location.pathname !== '/user/login' && !redirect) {
        window.location.reload()
        // history.replace({
        //   pathname: '/user/login'
        // });
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      if(payload.user.region.region === "楚雄州"){
        setAuthority('chuxiong')
      }else{
        setAuthority('admin')
      }
      localStorage.setItem('token', payload.token);
      return { ...state, status: payload.token ? 'success' : 'error' };
    },
  },
};
export default Model;
